#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use eframe::egui;
use tray_icon::{menu::{Menu, MenuEvent, MenuId, MenuItem}, Icon, TrayIcon, TrayIconBuilder, TrayIconEvent};
use std::cell::RefCell;
use std::rc::Rc;
use std::thread;

fn main() {

    let mut vp = egui::ViewportBuilder::default();
    vp.title = Some("Remote Control Root".to_string());
    vp.inner_size = Some(egui::vec2(400.0, 300.0));
    vp.resizable = Some(false);
    vp.minimize_button = Some(false);
    vp.maximize_button = Some(false);

    let mut _tray_icon = Rc::new(RefCell::new(None));
    let tray_c = _tray_icon.clone();
    let mut m = Rc::new(RefCell::new(Menu::new()));
   
    
    let icon_asset = Icon::from_path("d:\\code\\a3tub-xn5xd-001.ico".to_string(),Some((32,32))).unwrap();

    let native_options = eframe::NativeOptions{ 
        viewport: vp,
        ..Default::default() 
    };

 
    let _ = eframe::run_native("My egui App", native_options, Box::new(move |cc| { 

        #[cfg(not(target_os = "linux"))]
            {
                let mut x = m.borrow_mut();
                x.append(&MenuItem::with_id(MenuId::new("1001"),"Exit", true, None));

                let tray_icon = TrayIconBuilder::new()
                .with_menu(Box::new(x.clone()))
                .with_icon(icon_asset)
                .with_tooltip("Remote Control APP")
                .build().unwrap();
                tray_icon.set_visible(false);

                tray_c
                    .borrow_mut()
                    .replace(tray_icon);

                 
               
            }

      

            Ok(Box::new(MyApp::new(cc,m,tray_c)))
          
        }
        ));
}

#[derive(Default)]
struct MyApp {
    user: String,
    pwd: String,
    menu: Rc<RefCell<Menu>>,
    tray_icon: Rc<RefCell<Option<TrayIcon>>>,
}

impl MyApp {
    fn new(_cc: &eframe::CreationContext<'_>,m: Rc<RefCell<Menu>>,t: Rc<RefCell<Option<TrayIcon>>>) -> Self {
        let mut x = Self::default();
        x.user = String::new();
        x.pwd = String::new();
        x.menu = m;
        x.tray_icon = t;
        x
    }

}

impl eframe::App for MyApp {

    fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {

                        
        egui::CentralPanel::default().show(ctx,|ui| {

            egui::TopBottomPanel::bottom("bottom_panel").min_height(90.0).show_separator_line(false).show_inside(ui, |ui| {
                // ui.label("Hello World bottom_panel");
            });
    
            egui::TopBottomPanel::top("top_panel").show_separator_line(false).min_height(90.0).show_inside(ui, |ui| {
                ui.label("XXX Remote Control");   
            });

            egui::Grid::new("TextLayoutDemo")
            .num_columns(2)
            .min_row_height(30.0)
            .show(ui, |ui| {
                ui.label("User:");
                ui.add(egui::TextEdit::singleline(&mut self.user).hint_text("Enter your Email"));
                ui.end_row();
                ui.label("Password:");
                ui.add(egui::TextEdit::singleline(&mut self.pwd).password(true).hint_text("Enter your Password"));
                ui.end_row();
                let mut login_btn = egui::Button::new("Login");
                login_btn = login_btn.min_size(egui::vec2(100.0, 30.0));
                let login_btn_response = ui.add(login_btn);
                if login_btn_response.clicked(){
                    println!("Login button clicked");
                    println!("User: {}", self.user);
                    println!("Password: {}", self.pwd);
                    ui.ctx().send_viewport_cmd(egui::ViewportCommand::Visible(false));
                    let show = MenuItem::with_id(MenuId::new("1002"), "Show", true, None);
                    self.menu.borrow_mut().insert(&show,0);
                    self.tray_icon.borrow_mut().as_mut().unwrap().set_visible(true);

                    // let xui = ctx.clone();
                    // let x = ui.ctx().clone();

                    thread::spawn(move || { 
                         
                        loop{
                
                            if let Ok(event) = MenuEvent::receiver().try_recv() {
                                println!("menu event: {:?}", event);
                                if event.id() == "1002" {
                                    println!("Show clicked");
                                  
                                //    xui.send_viewport_cmd(egui::ViewportCommand::Visible(true));
                                    // self.tray_icon.borrow_mut().as_mut().unwrap().set_visible(false);
                                }
                            }
                    
                        }
                    });
                  
                };
                ui.end_row();
            });
    
       
            // ui.with_layout(egui::Layout::top_down(egui::Align::Center), |ui| {
                
            // });
        });
    }
}